 
from pymodbus.client.sync import ModbusTcpClient
from pymodbus.exceptions import ConnectionException
import time 


# Modbus TCP 服务器的IP和端口
SERVER_IP = 'hh.hhdata.cn'
SERVER_PORT = 31257

 

# 创建Modbus TCP客户端
client = ModbusTcpClient(SERVER_IP, port=SERVER_PORT)

try:
    # 连接到服务器
    connection = client.connect()
    if connection:
        print('Connected to Modbus TCP server')
        while 1>0 :
            time.sleep(1)            
        # 读取保持寄存器
            addr =  40000 + 4
            response = client.read_holding_registers(0x0022, 50, unit=0x01)
            if response.isError():
                print('Error reading holding registers:', response)
            else:
                print('Holding registers:', response.registers)  
    else:
        print('Failed to connect to Modbus TCP server')

except ConnectionException as ce:
    print('Connection failed:', ce)

except Exception as e:
    print('Error:', e)

finally:
    # 关闭连接
    client.close()
    print('Modbus TCP client connection closed')

